import 'dart:math';

import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/material.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/comment/comment_list_res.dart';
import 'package:xvideos/routers/jump_router.dart';

class QuickSearchView extends StatefulWidget {
  final List<CommentLink> dataSource;

  const QuickSearchView(this.dataSource, {super.key});

  @override
  State<StatefulWidget> createState() {
    return _QuickSearchViewState();
  }
}

class _QuickSearchViewState extends State<QuickSearchView> {
  CommentLink? model;
  final realQuickSearchs = <CommentLink>[];

  @override
  void initState() {
    super.initState();
    realQuickSearchs.addAll(widget.dataSource.where((e) => e.type == 2));
    loadData();
  }

  void loadData() {
    if (model == null && realQuickSearchs.isNotEmpty) {
      if (realQuickSearchs.length > 1) {
        final index = Random().nextInt(realQuickSearchs.length);
        model = realQuickSearchs[index];
      } else {
        model = realQuickSearchs.first;
      }
    }
  }

  @override
  void didUpdateWidget(covariant QuickSearchView oldWidget) {
    loadData();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    if (model == null) return SizedBox();
    return GestureDetector(
      onTap: () {
        pushToPageByLink(model?.link ?? '', arguments: {'id': model?.id});
      },
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Flexible(
            child: EasyRichText(
              '${model?.title ?? ''}',
              defaultStyle: TextStyle(color: Colors.white, fontSize: 14),
              patternList: [
                EasyRichTextPattern(
                    targetString: model?.searchKeyword ?? '', style: TextStyle(color: Color(0xffDB361F), fontSize: 14, height: 1))
              ],
            ),
          ),
          Image.asset(
            'hot_search.png'.communityPath,
            width: 9,
            height: 9,
          ),
        ],
      ),
    );
  }
}
